﻿using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;

public class AuthenticationStateService
{
    private readonly NavigationManager _navigationManager;
    private readonly IJSRuntime _jsRuntime;

    public AuthenticationStateService(
        NavigationManager navigationManager,
        IJSRuntime jsRuntime)
    {
        _navigationManager = navigationManager;
        _jsRuntime = jsRuntime;
    }

    // 获取 Token
    public async Task<string?> GetTokenAsync()
    {
        try
        {
            var token = await _jsRuntime.InvokeAsync<string>("localStorage.getItem", "token");
            Console.WriteLine($"Get Token: {token}");
            return token;
        }
        catch (JSException ex)
        {
            Console.WriteLine($"JS 错误: {ex.Message}");
            return null;
        }
    }

    // 检查是否已认证
    public async Task<bool> IsAuthenticatedAsync()
    {
        var token = await GetTokenAsync();
        return !string.IsNullOrEmpty(token);
    }

    // 如果未认证，跳转到登录页
    public async Task RedirectIfNotAuthenticatedAsync()
    {
        if (!await IsAuthenticatedAsync())
        {
            _navigationManager.NavigateTo("/login");
        }
    }

    // 设置 Token
    public async Task SetTokenAsync(string token)
    {
        Console.WriteLine($"Set Token: {token}");
        await _jsRuntime.InvokeVoidAsync("localStorage.setItem", "token", token);
    }

    // 移除 Token
    public async Task RemoveTokenAsync()
    {
        await _jsRuntime.InvokeVoidAsync("localStorage.removeItem", "token");
    }
}